# import cv2
# import time

# # 设置摄像头的分辨率和帧率
# width = 640
# height = 480
# framerate = 30

# # 创建 GStreamer 管道
# gs_pipeline = f"v4l2src device=/dev/video0 io-mode=2 " \
#               f"! image/jpeg, width={width}, height={height}, framerate={framerate}/1, format=MJPG " \
#               f"! nvv4l2decoder mjpeg=1 " \
#               f"! nvvidconv " \
#               f"! video/x-raw, format=BGRx " \
#               f"! videoconvert " \
#               f"! video/x-raw, format=BGR " \
#               f"! appsink drop=1"

# # 使用 GStreamer 管道打开摄像头
# cap = cv2.VideoCapture(gs_pipeline, cv2.CAP_GSTREAMER)

# # 检查摄像头是否打开
# if not cap.isOpened():
#     print("无法打开摄像头")
#     exit()

# # 计算帧率
# start_time = time.time()
# frame_count = 0
# fps = 0

# while True:
#     ret, frame = cap.read()
#     if not ret:
#         print("无法接收帧（流结束？）")
#         break

#     cv2.imshow('Hardware', frame)
#     if cv2.waitKey(1) == ord('q'):
#         break

#     frame_count += 1
#     if (time.time() - start_time) > 1:
#         fps = frame_count / (time.time() - start_time)
#         frame_count = 0
#         start_time = time.time()
#         print(f"当前帧率: {fps:.2f} FPS")

# # 释放摄像头资源
# cap.release()
# cv2.destroyAllWindows()

import cv2
import time

width = 640
height = 480

gs_pipeline = f"v4l2src device=/dev/video0 io-mode=2 " \
              f"! image/jpeg, width={width}, height={height}, framerate=30/1, format=MJPG " \
              f"! nvv4l2decoder mjpeg=1 " \
              f"! nvvidconv " \
              f"! video/x-raw, format=BGRx " \
              f"! videoconvert " \
              f"! video/x-raw, format=BGR " \
              f"! appsink drop=1"

cap = cv2.VideoCapture(gs_pipeline, cv2.CAP_GSTREAMER)


# 检查摄像头是否打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()


# 每0.1S计算一次帧率
t = 0.1
counter = 0
fps = 0
start_time = time.time()

while (True):
    ret, frame = cap.read()
    img = frame.copy()
    # 测帧率
    counter += 1
    if (time.time() - start_time) > t:
        fps = counter / (time.time() - start_time)
        fps = str(fps)
        counter = 0
        start_time = time.time()
    cv2.putText(frame, "FPS {0}".format(fps), (10, 30), 1, 1.5, (255, 0, 255), 2)

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
